/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kmcsoft.goldshop.shop;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.zkoss.zk.ui.Component;
import org.zkoss.zkplus.databind.TypeConverter;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;

/**
 *
 * @author kmcsoft02
 */
public class MultiItemConverter implements TypeConverter {

    @SuppressWarnings("unchecked")
    public Object coerceToBean(Object val, Component comp) {
        Set<Object> objects = new HashSet<Object>();
        if (comp instanceof Listbox) {
            Collection<Listitem> listitems = ((Listbox) comp).getSelectedItems();
            for (Listitem listitem : listitems) {
                objects.add(listitem.getValue());
            }
        }
        return objects;
    }

    @SuppressWarnings("unchecked")
    public Object coerceToUi(Object val, Component comp) {
        HashSet<Listitem> selectedItems = new HashSet<Listitem>(); // have to return a Set since MultiBinding/Listbox.get/setSelectedItems does same
        if (val instanceof Collection) {
            Collection values = (Collection) val;
            if (comp instanceof Listbox) {
                Listbox listbox = (Listbox) comp;
                listbox.clearSelection();
                List<Listitem> listitems = listbox.getItems();
                ListModel listModel = listbox.getModel();
                if (listModel != null) {
                    int size = listModel.getSize();
                    for (int i = 0; i < size; i++) {
                        Iterator iter = values.iterator();
                        while (iter.hasNext()) {
                            Object key = iter.next();
                            if (listModel.getElementAt(i).equals(key)) {
                                selectedItems.add(listitems.get(i));
                            }
                        }
                    }
                } else {
                    for (Listitem listitem : listitems) {
                        Iterator iter = values.iterator();
                        while (iter.hasNext()) {
                            Object key = iter.next();
                            if (listitem.getValue().equals(key)) {
                                selectedItems.add(listitem);
                            }
                        }
                    }
                }
            }
            ((Listbox) comp).setSelectedItems(selectedItems);
        }
        return selectedItems;
    }
}
